//
//  RecommendViewController.m
//  HeartTravel
//
//  Created by dlios on 15-6-29.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "RecommendViewController.h"
#import "Scroll.h"
#import "UIImageView+WebCache.h"
#import "AFNetworking.h"
#import "RecCell.h"
#import "RecT5Cell.h"
#import "RecType5.h"
#import "RecType4.h"
#import "RecType7.h"
#import "RecDetailViewController.h"
#import "UIButton+WebCache.h"
#import "CollectionViewCell.h"
#import "CarouselViewController.h"
#import "HTTPTool.h"
#import "MJRefresh.h"

@interface RecommendViewController ()<UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate>
@property(nonatomic,retain)UIView *headerView;
@property(nonatomic,retain)UICollectionView *collectionView;
@property(nonatomic,retain)UITableView *tableView;
@property(nonatomic,retain)NSMutableArray *tableArr;
@property(nonatomic,retain)NSNumber *next_start;
@property(nonatomic,retain)NSMutableArray *scrollArr;

@end

@implementation RecommendViewController
-(void)dealloc{
    [_headerView release];
    [_scrollArr release];
    [_tableArr release];
//    [_tableT5Arr release];
    [_collectionView release];
    [_tableView release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.next_start = nil;
    self.scrollArr=[NSMutableArray array];
    self.tableArr=[NSMutableArray array];
    
    self.navigationController.navigationBar.translucent=NO;
    self.headerView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,180)];
    
    [self.view addSubview:self.headerView];
    [self.headerView release];
    self.tableView=[[UITableView alloc]init];
    self.tableView.frame=CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-64-49);
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    self.tableView.rowHeight = 200;
    self.tableView.showsVerticalScrollIndicator=NO;
    self.tableView.showsHorizontalScrollIndicator=NO;
    self.tableView.tableHeaderView=self.headerView;
    
    
    [self.tableView addFooterWithTarget:self action:@selector(footerRefresh)];
    [self.tableView addHeaderWithTarget:self action:@selector(headerRefresh)];

    

    self.tableView.backgroundColor= [UIColor redColor];


   
    self.tableView.backgroundColor= [UIColor redColor];

    [self.view addSubview:self.tableView];
    [self creatDataRefresh];
    [self creatData];
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc]init];
    flowLayout.itemSize=CGSizeMake(self.headerView.frame.size.width, self.headerView.frame.size.height);
    flowLayout.minimumLineSpacing=0;
    //设置最小的列间距
    flowLayout.minimumInteritemSpacing=0;
    flowLayout.scrollDirection=UICollectionViewScrollDirectionHorizontal;
    self.collectionView=[[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.headerView.frame.size.width, self.headerView.frame.size.height)collectionViewLayout:flowLayout];
    self.collectionView.pagingEnabled=YES;
    self.collectionView.delegate=self;
    self.collectionView.dataSource=self;
     [self.collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    self.collectionView.backgroundColor=[UIColor whiteColor];
    [self.headerView addSubview:self.collectionView];
    [self.collectionView release];
    
}

- (void)footerRefresh{
    
    [self creatData];
}

- (void)headerRefresh{
    self.next_start = nil;
    [self creatData];
    [self creatDataRefresh];
}

- (void)creatDataRefresh{
    
    NSString *Url = @"http://api.breadtrip.com/v5/index/?is_ipad=0&lat=38.88287764798017&lng=121.5398279985663&sign=7d877a460e9b51fa552a74de7cdffe10";
    
    [HTTPTool get:Url body:nil httpResult:JSON success:^(id result) {
        

        NSDictionary *dic=result;
        //scrollView里的数据
        NSArray *eleArr=dic[@"elements"];
    
    NSDictionary *dataDic = eleArr[0];
    NSArray *dataArr=dataDic[@"data"];
    NSArray *arr=dataArr[0];
    for (NSDictionary*tempDic in arr) {
        Scroll *scroll=[[Scroll alloc]init];
        [scroll setValuesForKeysWithDictionary:tempDic];
        [self.scrollArr addObject:scroll];
        
    }
    NSString *lastImage = [self.scrollArr lastObject];
    [self.scrollArr insertObject:lastImage atIndex:0];
    NSString *firstImage = [self.scrollArr objectAtIndex:1];
    [self.scrollArr addObject:firstImage];
    
    [self.tableView footerEndRefreshing];
    
        NSLog(@"1");
//    [self.tableView reloadData];
    [self.collectionView reloadData];
} failure:^(NSError *error) {
    NSLog(@"%@",error);
}];



[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(changeImage) userInfo:nil repeats:YES];

}



//-(void)creatData{
//    
////    self.tableArr=[NSMutableArray array];
//    NSString *Url = @"http://api.breadtrip.com/v5/index/?is_ipad=0&lat=38.88287764798017&lng=121.5398279985663&sign=7d877a460e9b51fa552a74de7cdffe10";
//    if (self.next_start != nil) {
//        Url = [NSString stringWithFormat: @"http://api.breadtrip.com/v5/index/?is_ipad=0&lat=38.88287764798017&lng=121.5398279985663&next_start=%@&sign=7d877a460e9b51fa552a74de7cdffe10",self.next_start];
//    }
//    
//    [HTTPTool get:Url body:nil httpResult:JSON success:^(id result) {
//
//        NSDictionary *dic=result;
//        //scrollView里的数据
//        NSArray *eleArr=dic[@"elements"];
//    
//    NSDictionary *dataDic = eleArr[0];
//    NSArray *dataArr=dataDic[@"data"];
//    NSArray *arr=dataArr[0];
//    for (NSDictionary*tempDic in arr) {
//        Scroll *scroll=[[Scroll alloc]init];
//        [scroll setValuesForKeysWithDictionary:tempDic];
//        [self.scrollArr addObject:scroll];
//
//    }
//    NSString *lastImage = [self.scrollArr lastObject];
//    [self.scrollArr insertObject:lastImage atIndex:0];
//    NSString *firstImage = [self.scrollArr objectAtIndex:1];
//    [self.scrollArr addObject:firstImage];
//    
//    [self.tableView headerEndRefreshing];
//    
//    

////    [self.tableView reloadData];
//    [self.collectionView reloadData];

-(void)creatData{
    
//    self.tableArr=[NSMutableArray array];
    NSString *Url = @"http://api.breadtrip.com/v5/index/?is_ipad=0&lat=38.88287764798017&lng=121.5398279985663&sign=7d877a460e9b51fa552a74de7cdffe10";
    if (self.next_start != nil) {
        Url = [NSString stringWithFormat: @"http://api.breadtrip.com/v5/index/?is_ipad=0&lat=38.88287764798017&lng=121.5398279985663&next_start=%@&sign=7d877a460e9b51fa552a74de7cdffe10",self.next_start];
    }
    
    [HTTPTool get:Url body:nil httpResult:JSON success:^(id result) {
        NSDictionary *dic=result;
        //scrollView里的数据
        NSArray *eleArr=dic[@"elements"];
    
    NSDictionary *dataDic = eleArr[0];
    NSArray *dataArr=dataDic[@"data"];
    NSArray *arr=dataArr[0];
    for (NSDictionary*tempDic in arr) {
        Scroll *scroll=[[Scroll alloc]init];
        [scroll setValuesForKeysWithDictionary:tempDic];
        [self.scrollArr addObject:scroll];
        
    }
    NSString *lastImage = [self.scrollArr lastObject];
    [self.scrollArr insertObject:lastImage atIndex:0];
    NSString *firstImage = [self.scrollArr objectAtIndex:1];
    [self.scrollArr addObject:firstImage];
    
    [self.tableView headerEndRefreshing];
    
    

//    [self.tableView reloadData];
////    [self.collectionView reloadData];

//} failure:^(NSError *error) {
//    NSLog(@"%@",error);
//}];
//
//
//
//[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(changeImage) userInfo:nil repeats:YES];
//
//}


-(void)creatData{
    

    NSString *Url = @"http://api.breadtrip.com/v5/index/?is_ipad=0&lat=38.88287764798017&lng=121.5398279985663&sign=7d877a460e9b51fa552a74de7cdffe10";
    if (self.next_start != nil) {
        Url = [NSString stringWithFormat: @"http://api.breadtrip.com/v5/index/?is_ipad=0&lat=38.88287764798017&lng=121.5398279985663&next_start=%@&sign=7d877a460e9b51fa552a74de7cdffe10",self.next_start];
    }


        self.next_start = result[@"next_start"];
        

//-(void)creatData{
//    
////    self.tableArr=[NSMutableArray array];
//    NSString *Url = @"http://api.breadtrip.com/v5/index/?is_ipad=0&lat=38.88287764798017&lng=121.5398279985663&sign=7d877a460e9b51fa552a74de7cdffe10";
//    if (self.next_start != nil) {
//        Url = [NSString stringWithFormat: @"http://api.breadtrip.com/v5/index/?is_ipad=0&lat=38.88287764798017&lng=121.5398279985663&next_start=%@&sign=7d877a460e9b51fa552a74de7cdffe10",self.next_start];
//    }

//        self.next_start = result[@"next_start"];
//        
//
//
//        for (NSDictionary *dic in eleArr) {
//            if ([dic[@"type"] integerValue]!= 1) {
//                [self.tableArr addObject:dic];
//            }
//        }

        for (NSDictionary *dic in eleArr) {
            if ([dic[@"type"] integerValue]!= 1) {
                [self.tableArr addObject:dic];
            }
        }


    
    [HTTPTool get:Url body:nil httpResult:JSON success:^(id result) {
        NSDictionary *dic=result;
       
        NSArray *eleArr=dic[@"elements"];
        

        self.next_start = result[@"next_start"];
        


        for (NSDictionary *dic in eleArr) {
            if ([dic[@"type"] integerValue]!= 1) {
                [self.tableArr addObject:dic];
            }
        }
    
        

        

        [self.tableView reloadData];
        
        
        [self.tableView footerEndRefreshing];
        
        
        
//        [self.collectionView reloadData];
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
    
    
//    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(changeImage) userInfo:nil repeats:YES];
}

//    
//    [HTTPTool get:Url body:nil httpResult:JSON success:^(id result) {
//        NSDictionary *dic=result;
//       
//        NSArray *eleArr=dic[@"elements"];
//        
//        self.next_start = result[@"next_start"];
//        
//
//
//        for (NSDictionary *dic in eleArr) {
//            if ([dic[@"type"] integerValue]!= 1) {
//                [self.tableArr addObject:dic];
//            }
//        }
//    
//        
//        
//            [self.tableView reloadData];
//        
//        
//        [self.tableView footerEndRefreshing];
//        
//        
//        
////        [self.collectionView reloadData];
//    } failure:^(NSError *error) {
//        NSLog(@"%@",error);
//    }];
//    
//    
//    
////    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(changeImage) userInfo:nil repeats:YES];
//}

-(void)changeImage{
    [self.collectionView setContentOffset:CGPointMake(self.collectionView.contentOffset.x+self.headerView.frame.size.width, 0) animated:YES];
    if (self.collectionView.contentOffset.x ==  self.headerView.frame.size.width*(self.scrollArr.count-1)) {
        self.collectionView.contentOffset=CGPointMake(self.headerView.frame.size.width, 0);
    }
    
}
    
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.scrollArr.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    //使用了注册,就不需要判断是否为空
    
    //用sdwebimage对imageview进行图片赋值
    Scroll *scroll=self.scrollArr[indexPath.row];
        [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:scroll.image_url]];
    
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    CarouselViewController *carouselVC=[[CarouselViewController alloc]init];
    Scroll *scroll=self.scrollArr[indexPath.row];
    carouselVC.url=scroll.html_url;
    [self.navigationController pushViewController:carouselVC animated:YES];
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.tableArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *Celldic=self.tableArr[indexPath.row];
    NSArray *dataArr = Celldic[@"data"];
    NSDictionary *dic = dataArr[0];

    //
    if([Celldic[@"type"] integerValue] == 4){
        static NSString *T4Reuse=@"T4Reuse";
        RecCell *T4cell=[tableView dequeueReusableCellWithIdentifier:T4Reuse];
        if(!T4cell){
            T4cell=[[[RecCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:T4Reuse]autorelease];
        }
       
      
        RecType4 *type4 = [[RecType4 alloc] initWithDic:dic];

        T4cell.nameLabel.text = type4.name;
        [T4cell.backView sd_setImageWithURL:[NSURL URLWithString:type4.cover_image]];
        T4cell.dataLabel.text=type4.first_day;
        T4cell.timeLabel.text=[NSString stringWithFormat:@"%@ 天",type4.day_count.stringValue];
        T4cell.readLabel.text=[NSString stringWithFormat:@"%@  次浏览",type4.view_count.stringValue];
        T4cell.localLabel.text=type4.popular_place_str;
        T4cell.authorLabel.text=type4.user[@"name"];
        [T4cell.authorButton sd_setBackgroundImageWithURL:[NSURL URLWithString:type4.user[@"avatar_s"]] forState:UIControlStateNormal];
        return T4cell;
    }else  if([Celldic[@"type"] integerValue] == 5){
        static NSString *T5Reuse=@"T5Reuse";
        RecT5Cell *T5cell=[tableView dequeueReusableCellWithIdentifier:T5Reuse];
        if (!T5cell) {
            T5cell=[[[RecT5Cell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:T5Reuse]autorelease];
        }
        RecType5 *recType5 = [[RecType5 alloc] initWithDic:dic];
     
        [T5cell.backView sd_setImageWithURL:[NSURL URLWithString:recType5.cover]];
        T5cell.nameLabel.text = recType5.cover_title;
        T5cell.contentLabel.text=recType5.cover_sub_title;
        
        return T5cell;
    }else if ([Celldic[@"type"] integerValue] == 7){
        static NSString *T7Reuse=@"T7Reuse";
        RecT5Cell *T5cell=[tableView dequeueReusableCellWithIdentifier:T7Reuse];
        if (!T5cell) {
            T5cell=[[[RecT5Cell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:T7Reuse]autorelease];
        }
        RecType7 *recType7 = [[RecType7 alloc] init];
        [recType7 setValuesForKeysWithDictionary:dic];
        [T5cell.backView sd_setImageWithURL:[NSURL URLWithString:recType7.cover]];
        T5cell.nameLabel.text=recType7.sub_title;
//        T5cell.contentLabel.text=recType7.title;
        return T5cell;
    }else{
        return nil;
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    RecDetailViewController *recDVC=[[RecDetailViewController alloc]init];
    [self.navigationController pushViewController:recDVC animated:YES];
    NSDictionary *Celldic=self.tableArr[indexPath.row];
    NSArray *dataArr = Celldic[@"data"];
    NSDictionary *dic = dataArr[0];
     RecType4 *type4 = [[RecType4 alloc] initWithDic:dic];
    RecType5 *type5=[[RecType5 alloc]initWithDic:dic];
    for (NSInteger i = 0; i<self.tableArr.count; i++) {
        
        if ([Celldic[@"type"] integerValue] == 4) {
            recDVC.url=[NSString stringWithFormat:@"http://breadtrip.com/trips/%@/",type4.bId];
    }else{
        recDVC.url=type5.url;
    }
    }

}
    v


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
